<template>
  <div>
    <table>
      <thead>
        <tr>
          <th v-for="header in headers" :key="header">{{ header }}</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="job in jobs" :key="job.job_id">
          <td>{{ job.job_id }}</td>
          <td>{{ job.os }}</td>
          <td>{{ job.submit_time }}</td>
          <td>{{ job.queue_time }}</td>
          <td>{{ job.start_time }}</td>
          <td>{{ job.end_time }}</td>
          <td>{{ job.cpu_count }}</td>
          <td>{{ job.memory_gb }}</td>
          <td>{{ job.status }}</td>
          <td><div class="progress" :style="{ width: job.progress + '%' }"></div></td>
          <td>
            <button v-if="job.status !== 'waitting'" @click="$emit('show-task', job.job_id)">Task详情</button>
            <button v-if="job.status === 'waitting' || job.status === 'abort' || job.status === 'finish'" @click="runJob(job.job_id)">运行</button>
            <button v-if="job.status === 'runing'" @click="abortJob(job.job_id)">中止</button>
          </td>
        </tr>
      </tbody>
    </table>
    <div class="pagination">分页: {{ pageId }}</div>
  </div>
</template>

<script>
import { getJobList, runJob, abortJob } from '../api';

export default {
  props: ['envId'],
  data() {
    return {
      headers: [
        'Job编号', '运行操作系统', '提交时间', '排队时间', '开始时间', '结束时间',
        '占用cpu数量', '占用内存数量(GB)', 'status', '进度', '操作',
      ],
      jobs: [],
      pageId: 1,
    };
  },
  created() {
    this.fetchJobs();
  },
  methods: {
    async fetchJobs() {
      const res = await getJobList({ page_id: this.pageId, env_id: this.envId });
      this.jobs = res.data;
    },
    async runJob(jobId) {
      await runJob(jobId);
      alert('成功，已经进入排队等待调度');
      this.fetchJobs();
    },
    async abortJob(jobId) {
      await abortJob(jobId);
      alert('成功，正在执行中止操作');
      this.fetchJobs();
    },
  },
};
</script>

<style scoped>
.progress {
  height: 10px;
  background: #4caf50;
}
table {
  width: 100%;
  border-collapse: collapse;
}
th, td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: center;
}
button {
  margin: 0 5px;
}
.pagination {
  margin-top: 10px;
  text-align: center;
}
</style>
